﻿
using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.FormCategory;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.FormCategory
{
    /// <summary>
    /// 删除表单类别
    /// </summary>
    public class DelFormCategoryHandler : IRequestHandler<DelFormCategoryCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<FormCategoryModel> formCategoryRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DelFormCategoryHandler> logger;

        public DelFormCategoryHandler(IBaseRepository<FormCategoryModel> formCategoryRepo, IMapper mapper, ILogger<DelFormCategoryHandler> logger)
        {
            this.formCategoryRepo = formCategoryRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(DelFormCategoryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"您正在删除编号为{request.Id}的表单类别");
                var entity = await formCategoryRepo.GetModel(request.Id);//根据id查找到实体
                if (entity == null)
                {
                    logger.LogError($"您要删除的表单类别不存在.id:{request.Id}");
                    return new ApiResult<int>().Fail("您要删除的表单类别不存在");
                }

                //var model = mapper.Map<FormCategoryModel>(request);//把请求命令通过automapper 转成实体
                // entity = mapper.Map(request,entity);//把请求命令里的属性覆盖到查找到的实体属性
                entity.IsDeleted = true;


                int r = await formCategoryRepo.UpdateAsync(entity);

                if (r > 0)
                {
                    return new ApiResult<int>().Success("删除表单类别成功", r);
                }
                else
                {
                    logger.LogError($"删除表单类别失败.id:{request.Id}");
                    return new ApiResult<int>().Fail("删除表单类别失败");
                }
            }
            catch (Exception e)
            {
                logger.LogError($"删除表单类别失败.id:{request.Id},错误信息:{e.Message}");
                throw e;
            }

            
        }
    }
}
